from flask import Blueprint, render_template, redirect, url_for, flash, request, current_app
from flask_login import login_required, current_user
from app import db
from app.models.user import User
from app.models.question import Question
from app.models.answer import Answer
from app.forms.user_forms import EditProfileForm
from app.forms.question_forms import SearchForm
import os
from werkzeug.utils import secure_filename
from app.utils import FileUtil

user = Blueprint('user', __name__)

@user.route('/<username>')
def profile(username):
    user = User.query.filter_by(username=username).first_or_404()
    search_form = SearchForm()
    
    # 获取用户的问题
    page = request.args.get('page', 1, type=int)
    questions = Question.query.filter_by(user_id=user.id).paginate(
        page=page, per_page=current_app.config['QUESTIONS_PER_PAGE'], error_out=False)
    
    return render_template('user/profile.html', 
                        user=user, 
                        questions=questions,
                        search_form=search_form)

@user.route('/edit-profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
    form = EditProfileForm()
    search_form = SearchForm()
    
    if form.validate_on_submit():
        current_user.username = form.username.data
        current_user.email = form.email.data
        current_user.about_me = form.about_me.data
        
        # 处理头像上传
        if form.avatar.data:
            # 使用FileUtil工具类保存头像
            avatar_path = os.path.join(current_app.root_path, 'static/img/avatars')
            filename = FileUtil.save_file(
                form.avatar.data, 
                avatar_path, 
                allowed_extensions={'jpg', 'jpeg', 'png'}
            )
            
            if filename:
                current_user.avatar = f'avatars/{filename}'
        
        db.session.commit()
        flash('个人资料已更新', 'success')
        return redirect(url_for('user.profile', username=current_user.username))
    
    # 表单预填充
    form.username.data = current_user.username
    form.email.data = current_user.email
    form.about_me.data = current_user.about_me
    
    return render_template('user/edit_profile.html', 
                          form=form,
                          search_form=search_form)

@user.route('/<username>/answers')
def user_answers(username):
    user = User.query.filter_by(username=username).first_or_404()
    search_form = SearchForm()
    
    # 获取用户的回答
    page = request.args.get('page', 1, type=int)
    answers = Answer.query.filter_by(user_id=user.id).paginate(
        page=page, per_page=current_app.config['QUESTIONS_PER_PAGE'], error_out=False)
    
    return render_template('user/answers.html', 
                          user=user, 
                          answers=answers,
                          search_form=search_form) 